<?php

namespace App\Services\WxUser;

use App\Facades\EasyWechat;
use App\Models\WxUserTag;
use App\Services\WxCommon\WxError;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

/**
 * 微信用户标签服务类
 * @package App\Services
 */
class WxUserTagService extends \App\Services\WxCommon\WxBase
{
    /**
     * 获取标签列表
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getTagList()
    {
        $tagList = WxUserTag::where('appid', $this->appid)->get();
        return $tagList;
    }

    /**
     * 获取缓存标签数据列表
     * @param bool $refresh
     * @return \Illuminate\Database\Eloquent\Collection|mixed|static[]
     */
    public function getCacheTagList($refresh = false)
    {
        $cacheKey = 'wxuser_taglist_'.$this->appid;
        //Cache::delete($cacheKey);
        $tagList = Cache::get($cacheKey);
        if (!$tagList || $refresh){
            $tagList = $this->getTagList()->toArray();
            Cache::put($cacheKey, $tagList, 60);
        }
        return $tagList;
    }

    /**
     * 获取select options的html字符
     * @return string
     */
    public function getSelectOptionHtml()
    {
        $findlist = $this->getCacheTagList();
        $tree = new \App\Services\Tool\TreeService('tag_id','parent_id','children');
        $tree->valKey = 'wx_tag_id';
        $tree->nameKey = 'tag_name';
        $tree->load($findlist);
        $optionHtml = $tree->buildOptions();
        return $optionHtml;
    }
    /**
     * 获取以微信端标签ID为key的标签名称列表
     * @return array
     */
    public function getTagNameListByWxTagId()
    {
        $taglist = $this->getCacheTagList(true);
        $arr = [];
        if ($taglist){
            $arr = array_combine(array_column($taglist, 'wx_tag_id'), array_column($taglist, 'tag_name'));
        }
        return $arr;
    }
    /**
     * 保存标签数据
     * @param $request
     * @return bool
     * @throws \Exception
     */
    public function saveData($request)
    {
        $tagId = $request->input('tag_id', 0);
        Db::beginTransaction();
        try {
            $app = EasyWechat::officialAccount($this->appid);
            if ($tagId) {//编辑
                $tagModel = WxUserTag::findOrFail($tagId);
                $apiRs = $app->user_tag->update($tagModel['wx_tag_id'], $request->tag_name);
            } else {//添加
                $tagModel = new WxUserTag;
                $apiRs = $app->user_tag->create($request->tag_name);
                $tagModel->wx_tag_id = $apiRs['tag']['id'] ?? 0;
                $tagModel->user_count = 0;
            }
            WxError::checkApiResponse($apiRs);
            $tagModel->appid = $this->appid;
            $tagModel->tag_name = $request->tag_name;
            $tagModel->parent_id = (int)$request->parent_id;
            $tagModel->order_num = (int)$request->order_num;
            $tagModel->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            throw new \Exception($e->getMessage());
        }
        //刷新标签缓存
        $this->getCacheTagList(true);
        return true;
    }

    /**
     * 删除标签
     * @param $tagId
     * @return bool
     * @throws \Exception
     */
    public function del($tagId)
    {
        Db::beginTransaction();
        try {
            $tag = EasyWechat::officialAccount($this->appid)->user_tag;
            $errConf = [
                -1 => '系统繁忙',
                45058 => '不能修改0/1/2这三个系统默认保留的标签',
                45057 => '该标签下粉丝数超过10w，不允许直接删除',
            ];
            $tagModel = WxUserTag::findOrFail($tagId);
            if (empty($tagModel)){
                throw new \Exception('标签不存在');
            }
            $tag->delete($tagModel['wx_tag_id']);
            if (!empty($apiRs['errcode'])) {
                $errmsg = isset($errConf[$apiRs['errcode']]) ? $errConf[$apiRs['errcode']] : $apiRs['errmsg'];
                throw new \Exception($errmsg);
            }

            $tagModel->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            throw new \Exception($e->getMessage());
        }
        //刷新标签缓存
        $this->getCacheTagList(true);
        return true;
    }

    /**
     * 同步线上标签
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function sync()
    {
        $tagList = EasyWechat::officialAccount($this->appid)->user_tag->list();
        if (!empty($tagList['tags'])) {
            Db::beginTransaction();
            try {
                WxUserTag::where('appid', $this->appid)->where('tag_id', '>', 0)->delete();
                foreach ($tagList['tags'] as $tag) {
                    $tagModel = WxUserTag::withTrashed()->where('appid', $this->appid)->where('wx_tag_id', $tag['id'])->first();
                    if ($tagModel) {

                    } else {
                        $tagModel = new WxUserTag;
                        $tagModel->wx_tag_id = $tag['id'];
                        $tagModel->parent_id = 0;
                    }
                    $tagModel->appid = $this->appid;
                    $tagModel->tag_name = $tag['name'] ?? '';
                    $tagModel->user_count = $tag['count'] ?? 0;
                    $tagModel->save();
                    $tagModel->restore();
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollBack();
                throw new \Exception($e->getMessage());
            }
        }
        //刷新标签缓存
        $this->getCacheTagList(true);
        return true;
    }
}